<template>
  <div class="goods-detail-container">
    <!-- 商品信息区域 -->
    <div class="goods-info-section">
      <el-card class="goods-info-card">
        <el-row gutter="30">
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
            <div class="goods-img-container">
              <!-- 图片轮播 -->
              <el-carousel
                v-if="displayImages.length > 0"
                height="400px"
                indicator-position="inside"
                arrow="hover"
                class="goods-carousel"
              >
                <el-carousel-item
                  v-for="(image, index) in displayImages"
                  :key="index"
                >
                  <el-image :src="image" fit="cover" class="carousel-image" />
                </el-carousel-item>
              </el-carousel>
              <!-- 单张图片显示 -->
              <el-image
                v-else
                :src="goods.mainImage"
                fit="cover"
                class="single-image"
              />
            </div>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
            <div class="goods-details">
              <h2 class="goods-title">{{ goods.goodsName }}</h2>
              <div class="goods-stats">
                <span class="stat-item">库存：{{ goods.stock }}</span>
                <span class="stat-item">销量：{{ goods.sales }}</span>
              </div>
              <div class="price-section">
                <el-link
                  type="danger"
                  :underline="false"
                  class="original-price"
                >
                  ￥{{ goods.originalPrice }}
                </el-link>
                <el-link
                  type="primary"
                  :underline="false"
                  class="current-price"
                >
                  ￥{{ goods.price }}
                </el-link>
              </div>

              <!-- 加入购物车按钮 -->
              <div class="cart-section">
                <el-button
                  type="success"
                  size="large"
                  icon="el-icon-shopping-cart-2"
                  @click.native="
                    dialogVisibleCount = true;
                    isJoinCart = true;
                  "
                  :loading="cartLoading"
                  :disabled="!currentUserId"
                >
                  {{ currentUserId ? "加入购物车" : "请先登录" }}
                </el-button>
                <el-button
                  type="primary"
                  size="large"
                  icon="el-icon-shopping-bag-1"
                  @click.native="
                    dialogVisibleCount = true;
                    isJoinCart = false;
                  "
                  :disabled="!currentUserId"
                >
                  立即购买
                </el-button>
              </div>

              <!-- 商品操作按钮 点赞收藏-->
              <GoodActions
                ref="goodActions"
                :goods-id="goods.id || $route.params.id"
                :user-id="currentUserId"
                :initial-like-count="goods.likes || 0"
                :initial-favorite-count="goods.favorites || 0"
                :initial-is-liked="goods.isLiked || false"
                :initial-is-favorited="goods.isFavorited || false"
                @like-change="handleLikeChange"
                @favorite-change="handleFavoriteChange"
              />
            </div>
          </el-col>
        </el-row>

        <!-- 商品描述和卖家信息另起一行 -->
        <el-row>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <div class="additional-info">
              <!-- 商品描述 -->
              <div class="description-section">
                <h3 class="section-title">商品描述</h3>
                <div class="description-content">
                  {{ goods.description || "暂无描述" }}
                </div>
              </div>

              <!-- 卖家信息 -->
              <div class="seller-section">
                <h3 class="section-title">卖家信息</h3>
                <div class="seller-info">
                  <div class="seller-avatar">
                    <el-avatar
                      :size="50"
                      :src="goods.userAvatar || sellerAvatar"
                      @error="handleAvatarError"
                    />
                  </div>
                  <div class="seller-details">
                    <div class="seller-name" @click="goToSellerPage">
                      <span class="seller-username">{{ goods.userName }}</span>
                      <i class="el-icon-arrow-right"></i>
                    </div>
                    <div class="seller-actions">
                      <el-button
                        size="small"
                        type="primary"
                        @click="contactSeller"
                        icon="el-icon-message"
                      >
                        联系卖家
                      </el-button>
                      <el-button
                        size="small"
                        :type="isFollowing ? 'danger' : 'default'"
                        @click="toggleFollow"
                        :icon="
                          isFollowing ? 'el-icon-star-off' : 'el-icon-star-on'
                        "
                      >
                        {{ isFollowing ? "取消关注" : "关注卖家" }}
                      </el-button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </el-card>
    </div>

    <!-- 评论区域 -->
    <div class="comment-section">
      <CommentSection
        :goods-id="$route.params.id"
        :current-user-id="currentUserId"
        @comment-added="handleCommentAdded"
        @comment-deleted="handleCommentDeleted"
      />
    </div>


    <el-dialog
      :visible="dialogVisibleCount"
      width="400px"
      @close="dialogVisibleCount = false"
    >
      <template slot="title">
        <span> <i class="el-icon-warning-outline"></i>&nbsp;提示</span>
      </template>
      <span style="font-size: 14px">
        请选择购买数量：
        <el-input-number
          size="small"
          v-model="goodsCount"
          :min="1"
          :max="goods.stock"
        ></el-input-number>
      </span>
      <template slot="footer">
        <el-button @click="dialogVisibleCount = false" size="mini"
          >取消</el-button
        >
        <el-button type="primary" @click="confirmDialog" size="mini"
          >确定</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.goods-detail-container {
  background-color: #f7f7f7;
  min-height: 100vh;
  padding: 20px 0;
}

/* 商品信息区域 */
.goods-info-section {
  max-width: 1000px;
  width: 100%;
  margin: 0 auto 20px auto;
  box-sizing: border-box;
}

.goods-info-card {
  background: white;
  border-radius: 20px;
  border: none;
  overflow: hidden;
}

.goods-info-card .el-card__body {
  padding: 30px;
}

/* 商品图片容器样式 */
.goods-img-container {
  width: 100%;
  background-color: #f5f5f5;
  border-radius: 10px;
  position: relative;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: transform 0.3s ease;
}

.goods-img-container:hover {
  transform: scale(1.02);
}

.goods-carousel {
  width: 100%;
  border-radius: 10px;
  overflow: hidden;
}

.carousel-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.single-image {
  width: 100%;
  height: 400px;
  object-fit: cover;
  border-radius: 10px;
}

.goods-details {
  padding-left: 0;
  display: flex;
  flex-direction: column;
  gap: 20px;
  text-align: left;
  height: 400px;
  justify-content: space-between;
}

.additional-info {
  padding: 0 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
  text-align: left;
  margin-top: 20px;
  width: 100%;
  box-sizing: border-box;
}

/* 商品信息样式 */
.goods-title {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 10px;
  line-height: 1.3;
  color: #2c3e50;
  text-align: left;
}

/* 商品描述和卖家信息区域 */
.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin: 0 0 10px 0;
  padding-bottom: 5px;
  text-align: left;
}

.description-section {
  margin-top: 0;
  width: 100%;
}

.description-content {
  line-height: 1.5;
  color: #666;
  font-size: 14px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  text-align: left;
  width: 100%;
  box-sizing: border-box;
  min-height: 80px;
}

/* 卖家信息样式 */
.seller-section {
  margin-top: 0;
  width: 100%;
}

.seller-info {
  display: flex;
  align-items: center;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  text-align: left;
  width: 100%;
  box-sizing: border-box;
}

.seller-avatar {
  margin-right: 15px;
}

.seller-details {
  flex: 1;
}

.seller-name {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 600;
  color: #333;
  text-align: left;
}

.seller-username {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-right: 8px;
  text-align: left;
}

.seller-actions {
  display: flex;
  gap: 10px;
  text-align: left;
}

.seller-actions .el-button {
  font-size: 12px;
  padding: 8px 16px;
  border-radius: 8px;
}

.seller-actions .el-button--primary {
  background-color: #00caa8 !important;
  border-color: #00caa8 !important;
}

.seller-actions .el-button--primary:hover {
  background-color: #00b894 !important;
  border-color: #00b894 !important;
}

.seller-actions .el-button--default {
  color: #00caa8 !important;
  border-color: #00caa8 !important;
}

.seller-actions .el-button--default:hover {
  color: #00b894 !important;
  border-color: #00b894 !important;
  background-color: #f0fdfa !important;
}

.goods-stats {
  margin-bottom: 15px;
  text-align: left;
}

.stat-item {
  display: inline-block;
  font-size: 14px;
  margin-right: 15px;
  padding: 5px 10px;
  background: #f8f9fa;
  color: #666;
  border-radius: 6px;
  font-weight: 500;
}

.price-section {
  margin-top: 10px;
  margin-bottom: 15px;
  text-align: left;
}

.original-price {
  font-size: 16px !important;
  margin-right: 15px !important;
  text-decoration-line: line-through !important;
  color: #999 !important;
}

.current-price {
  font-size: 28px !important;
  font-weight: 600 !important;
  color: #e74c3c !important;
}
/*购物车*/
.cart-section {
  margin-top: 15px;
  display: flex;
  gap: 15px;
  text-align: left;
}

.cart-section .el-button {
  flex: 1;
  height: 45px;
  font-size: 16px;
  font-weight: 500;
  border-radius: 10px;
  transition: all 0.3s ease;
}

.cart-section .el-button--success {
  background-color: #00caa8 !important;
  border-color: #00caa8 !important;
}

.cart-section .el-button--success:hover {
  background-color: #00b894 !important;
  border-color: #00b894 !important;
}

.cart-section .el-button--primary {
  background-color: #00caa8 !important;
  border-color: #00caa8 !important;
}

.cart-section .el-button--primary:hover {
  background-color: #00b894 !important;
  border-color: #00b894 !important;
}

.cart-section .el-button:hover {
  transform: translateY(-1px);
}

/* 内容简介样式 */
.el-form-item {
  margin-top: 20px;
}

/* 评论区域 */
.comment-section {
  max-width: 1000px;
  width: 100%;
  margin: 0 auto;
  background: white;
  border-radius: 20px;
  border: none;
  overflow: hidden;
  box-sizing: border-box;
}

/* 轮播图样式 */
/deep/ .el-carousel__indicators {
  bottom: 20px;
  z-index: 1;
}

/deep/ .el-carousel__arrow {
  background-color: rgba(0, 0, 0, 0.3);
  border-radius: 50%;
  color: white;
  font-size: 18px;
  width: 40px;
  height: 40px;
  line-height: 40px;
  z-index: 1;
}

/deep/ .el-carousel__arrow:hover {
  background-color: rgba(0, 0, 0, 0.5);
}

/* 确保对话框在最上层 */
/deep/ .el-dialog__wrapper {
  z-index: 9999 !important;
}

/deep/ .el-dialog {
  z-index: 10000 !important;
}

/* 确保遮罩层在最上层 */
/deep/ .el-overlay {
  z-index: 9998 !important;
}
</style>

<script>
import GoodActions from "./components/GoodActions.vue";
import CommentSection from "./components/CommentSection.vue"; // 导入 CommentSection 组件

export default {
  name: "GoodDetail",
  components: {
    GoodActions,
    CommentSection, // 注册 CommentSection 组件
  },
  data() {
    return {
      goods: {
        isLiked: false,
        isFavorited: false,
        likes: 0,
        favorites: 0,
      },
      dialogVisibleCount: false,
      goodsCount: 1,
      sellerAvatar:
        "https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png", // 默认头像
      isFollowing: false, // 是否已关注卖家
      cartLoading: false, // 购物车加载状态
      isJoinCart: false,
    };
  },
  computed: {
    currentUserId() {
      return this.$store.state.user.userId || null;
    },
    // 处理显示图片列表
    displayImages() {
      const images = [];

      // 添加主图
      if (this.goods.mainImage) {
        images.push(this.goods.mainImage);
      }

      // 解析并添加其他图片
      if (this.goods.images) {
        try {
          const parsedImages = JSON.parse(this.goods.images);
          if (Array.isArray(parsedImages)) {
            images.push(...parsedImages);
          }
        } catch (error) {
          console.error("解析图片数组失败:", error);
        }
      }

      return images;
    },
  },
  mounted() {
    this.fetchGoodsDetail();
  },
  watch: {
    // 监听用户登录状态变化
    currentUserId: {
      handler(newVal, oldVal) {
        if (newVal !== oldVal && this.goods.id) {
          if (newVal) {
            // 用户登录，检查状态
            this.checkUserActions();
          } else {
            // 用户登出，重置状态
            this.goods.isLiked = false;
            this.goods.isFavorited = false;
          }
        }
      },
      immediate: false,
    },
  },
  methods: {
    handleCommentAdded() {},
    handleCommentDeleted() {},
    confirmDialog() {
      if (this.isJoinCart) {
        this.joinCart();
      } else {
        this.buyNow();
      }
    },
    //立即购买
    async buyNow() {
      try {
        //获取当前用户选择的购物车商品
        let res = await this.$axios.get(
          `/cart/getUserCart/${this.$store.state.user.userId}`
        );
        let cartList = res.data.data;
        //将其他购物车商品设为未选
        await Promise.all(
          cartList.map((item) =>
            this.$axios.post("/cart/update", {
              cartId: item.cartId,
              selected: false,
            })
          )
        );
        //加入购物车
        let uid = this.$store.state.user.userId;
        res = await this.$axios.post("/cart/add", {
          userId: uid,
          productId: this.goods.id,
          productName: this.goods.goodsName,
          productPrice: this.goods.price,
          quantity: this.goodsCount,
          selected: true,
        });
        //跳转到创建订单页
        this.$router.push("/placeOrders");
      } catch (err) {
        this.$message.error(err);
      }
    },
    fetchGoodsDetail() {
      const id = this.$route.params.id;
      if (!id) return;
      this.$axios
        .get(`/goods/detail/${id}`)
        .then((resp) => {
          if (resp && resp.status === 200 && resp.data && resp.data.data) {
            this.goods = resp.data.data;
            // 确保商品对象有必要的属性
            this.goods.isLiked = this.goods.isLiked || false;
            this.goods.isFavorited = this.goods.isFavorited || false;
            this.goods.likes = this.goods.likes || 0;
            this.goods.favorites = this.goods.favorites || 0;

            // 获取商品详情后，确保有商品ID和用户ID时再检查状态
            this.$nextTick(() => {
              this.checkFollowStatus();
              this.checkLikeStatus();
              this.checkFavoriteStatus();
            });
          } else {
            this.goods = {
              isLiked: false,
              isFavorited: false,
              likes: 0,
              favorites: 0,
            };
          }
        })
        .catch(() => {
          this.goods = {
            isLiked: false,
            isFavorited: false,
            likes: 0,
            favorites: 0,
          };
        });
    },

    handleLikeChange(data) {
      // 更新商品数据中的点赞信息
      this.goods.isLiked = data.isLiked;
      this.goods.likes = data.likeCount;
    },

    handleFavoriteChange(data) {
      // 更新商品数据中的收藏信息
      this.goods.isFavorited = data.isFavorited;
      this.goods.favorites = data.favoriteCount;
    },

    // 处理头像加载错误
    handleAvatarError() {
      // 当用户头像加载失败时，使用默认头像
      this.goods.userAvatar =
        "https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png";
    },

    // 跳转到卖家主页
    goToSellerPage() {
      if (this.goods.userId) {
        this.$router.push(`/userCenter/${this.goods.userId}`);
      }
    },

    // 联系卖家
    contactSeller() {
      if (this.goods.userId) {
        // 跳转到聊天页面
        this.$router.push({
          name: 'ChatWithProduct',
          params: {
            productId: this.goods.id,
            sellerId: this.goods.userId,
            productName: this.goods.goodsName
          }
        });
      } else {
        this.$message.warning('卖家信息不完整');
      }
    },

    // 关注/取消关注卖家
    toggleFollow() {
      if (!this.goods.userId) {
        this.$message.warning("卖家信息不完整");
        return;
      }

      const userId = this.goods.userId;
      const action = this.isFollowing ? "取消关注" : "关注";

      if (!this.isFollowing) {
        // 关注
        this.$axios
          .post("/follow/confirmFollow", { id: userId })
          .then((resp) => {
            if (
              resp &&
              resp.status === 200 &&
              resp.data &&
              resp.data.code === 200
            ) {
              this.isFollowing = true;
              this.$message.success(`${action}成功`);
            } else {
              this.$message.error(`${action}失败`);
            }
          })
          .catch(() => {
            this.$message.error(`${action}失败，请稍后重试`);
          });
      } else {
        // 取消关注
        this.$axios
          .delete(`/follow/cancle/${userId}`)
          .then((resp) => {
            if (
              resp &&
              resp.status === 200 &&
              resp.data &&
              resp.data.code === 200
            ) {
              this.isFollowing = false;
              this.$message.success(`${action}成功`);
            } else {
              this.$message.error(`${action}失败`);
            }
          })
          .catch(() => {
            this.$message.error(`${action}失败，请稍后重试`);
          });
      }
    },

    // 检查是否已关注卖家
    checkFollowStatus() {
      if (this.goods.userId && this.currentUserId) {
        this.$axios
          .get(`/follow/is/${this.goods.userId}`)
          .then((resp) => {
            if (
              resp &&
              resp.status === 200 &&
              resp.data &&
              resp.data.code === 200
            ) {
              this.isFollowing = !!resp.data.data;
            } else {
              this.isFollowing = false;
            }
          })
          .catch(() => {
            this.isFollowing = false;
          });
      }
    },

    // 检查是否已点赞商品
    checkLikeStatus() {
      if (this.goods.id && this.currentUserId) {
        this.$axios
          .get(
            `/like/goods/check?userId=${this.currentUserId}&goodsId=${this.goods.id}`
          )
          .then((resp) => {
            if (resp && resp.status === 200) {
              this.goods.isLiked = !!resp.data.data;
              // 强制更新 GoodActions 组件状态
              this.forceUpdateGoodActions();
            }
          })
          .catch(() => {
            this.goods.isLiked = false;
            // 即使出错也要更新组件状态
            this.forceUpdateGoodActions();
          });
      } else {
        this.goods.isLiked = false;
        // 没有用户ID时也要更新组件状态
        this.forceUpdateGoodActions();
      }
    },

    // 检查是否已收藏商品
    checkFavoriteStatus() {
      if (this.goods.id && this.currentUserId) {
        this.$axios
          .get(
            `/favorite/check?userId=${this.currentUserId}&goodsId=${this.goods.id}`
          )
          .then((resp) => {
            if (resp && resp.status === 200) {
              this.goods.isFavorited = !!resp.data.data;
              // 强制更新 GoodActions 组件状态
              this.forceUpdateGoodActions();
            }
          })
          .catch(() => {
            this.goods.isFavorited = false;
            // 即使出错也要更新组件状态
            this.forceUpdateGoodActions();
          });
      } else {
        this.goods.isFavorited = false;
        // 没有用户ID时也要更新组件状态
        this.forceUpdateGoodActions();
      }
    },

    // 强制更新 GoodActions 组件状态
    forceUpdateGoodActions() {
      // 使用双重 nextTick 确保响应式更新完成
      this.$nextTick(() => {
        this.$nextTick(() => {
          if (this.$refs.goodActions) {
            // 直接传递最新的状态值
            this.$refs.goodActions.updateLocalState(
              this.goods.isLiked,
              this.goods.isFavorited,
              this.goods.likes,
              this.goods.favorites
            );
          }
        });
      });
    },
    joinCart() {
      let uid = this.$store.state.user.userId;
      this.$axios
        .post("/cart/add", {
          userId: uid,
          productId: this.goods.id,
          productName: this.goods.goodsName,
          productPrice: this.goods.price,
          quantity: this.goodsCount,
          selected: true,
        })
        .then((resp) => {
          // console.log(resp);
          if (resp.data.success) {
            this.$message.success(resp.data.message);
            this.dialogVisibleCount = false;
          } else {
            this.$message.error(resp.data.message);
          }
        });
    },
  },
  enterUserCenter(id) {
    this.$router.push({
      name: "UserCenter",
      params: {
        id: 1,
      },
    });
  },
};
</script>
